package com.jdbc;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by CCX on 2018/7/8.
 */
public class BeanListHandler<T> implements ResultSetHandler<List<T>>{
    private Class<T> classType;
    public BeanListHandler(Class<T> classType) {
        this.classType=classType;
    }
    public List<T> handle(ResultSet rs) throws SQLException {
        List<T> list=new ArrayList<T>();
        try {
        while(rs.next()) {
            T obj=classType.newInstance();
            BeanInfo beanInfo= Introspector.getBeanInfo(classType, Object.class);
            PropertyDescriptor[] pds=beanInfo.getPropertyDescriptors();
            for(PropertyDescriptor pd:pds) {
                String columnName=pd.getName();
                Object val=rs.getObject(columnName);
                pd.getWriteMethod().invoke(obj, val);
            }
            list.add(obj);
        }
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (IntrospectionException e) {
        e.printStackTrace();
    }
        return list;
    }

}